package controllers

import (
	"crypto/md5"
	"fmt"
	"github.com/astaxie/beego"
)

type LoginController struct {
	beego.Controller
}

func (this *LoginController) Get() {
	// 退出登录
	if this.Input().Get("exit") == "true" {
		this.DestroySession()
	}
	this.TplName = "login.html"
}

func (this *LoginController) Post() {
	//this.Ctx.WriteString(fmt.Sprint(this.Input()))
	uname := this.Input().Get("uname")
	pwd := this.Input().Get("pwd")
	autologin := this.Input().Get("autologin") == "on"

	if beego.AppConfig.String("uname") != uname || beego.AppConfig.String("pwd") != pwd {
		// TODO 账号密码错误
		this.Ctx.WriteString("账号密码有误")
		return
	}
	// 设置自动登录
	if autologin {
		userInfoKey := uname + pwd + beego.AppConfig.String("appname")
		hasStr := fmt.Sprint("%x", md5.Sum([]byte(userInfoKey)))
		this.GetSecureCookie("user_info_key", hasStr)
	}

	// 设置登录成功session
	this.SetSession("login_status", 1)
	this.SetSession("login_name", uname)

	this.Redirect("/", 301)
	return
}

func checkLoginStatus(ctx beego.Controller) bool {
	return ctx.GetSession("login_status") == 1
}
